package com.saxon.blog.shiro;

import com.saxon.blog.pojo.User;
import com.saxon.blog.service.user.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.HashMap;
import java.util.Map;

public class RealmConfig extends AuthorizingRealm {
    private UserServiceImpl userService;

    @Autowired
    public void setUserService (UserServiceImpl userService) {
        this.userService = userService;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo ();
        Subject subject = SecurityUtils.getSubject ();
        User user = (User) subject.getPrincipal ();
        simpleAuthorizationInfo.addStringPermission (user.getUserRole ()+"");
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        Map<String, Object> map = new HashMap<> ();
        map.put ("userName", usernamePasswordToken.getUsername ());
        User user = userService.getUser (map);
        if (user == null) {
            return null;
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo (user, user.getUserPassword (), "");
        return simpleAuthenticationInfo;
    }
}
